//
//  SMSDetailVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/5/13.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SVProgressHUD
class SMSDetailVC: RootVC {
    private var phoneNum : String?
    private var list : [SMSListModel.Message] = []
    private lazy var chatModel: ChatModel = {
        let model = ChatModel()
        model.isGroupChat = false
        return model
    }()
    
    private lazy var inputTF: ReceiverInputView = {
        let view = ReceiverInputView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: 50))
        view.backgroundColor = whiteColor
        view.textChangedHandle = ({[weak self] num in
            self?.phoneNum = num
        })
        return view
    }()
    
    private lazy var bgView: UIScrollView = {
        let view = UIScrollView(frame: CGRect(x: 0, y: isEmpty(string: phoneNum) ? inputTF.bottom : naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom - (isEmpty(string: phoneNum) ? inputTF.height : 0)))
        view.backgroundColor = colorRGBA(red: 245, green: 245, blue: 245, alpha: 1)
        view.contentSize = view.size
        view.isScrollEnabled = false
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y:0, width: screenWidth, height: bgView.height - inputV.height), style: .grouped)
        tab.backgroundColor = clearColor
        tab.rowHeight = 50
        tab.register(UUMessageCell.self, forCellReuseIdentifier: "cell")
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        return tab
    }()
    
    private lazy var inputV: UUInputFunctionView = {
        let view = UUInputFunctionView(frame: CGRect(x: 0, y: phoneBottom - naviView!.bottom - 60 , width: screenWidth, height: 60))
        view.bottom = bgView.height
        view.delegate = self
        view.backgroundColor = whiteColor
        return view
    }()
    
    init(phone:String? = nil,list:[SMSListModel.Message] = []) {
        super.init(nibName: nil, bundle: nil)
        self.list = list
        phoneNum = phone
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func configView() {
        configNaviView(title: isEmpty(string: phoneNum) ? "New SMS" : phoneNum)
        if isEmpty(string: phoneNum) {
            view.addSubview(inputTF)
        }
        view.addSubview(bgView)
        bgView.addSubview(tableView)
        bgView.addSubview(inputV)
        getData()
    }
    
    private func getData() {
        guard list.count > 0 else {
            return
        }
        
        let messages = list.map{ m -> UUMessageFrame in
            let uumf = UUMessageFrame()
            let uum = UUMessage()
            uum.strContent = m.content == nil ? "" : m.content!.unicodeStr
            let timearr = m.date!.components(separatedBy: ",")
            uum.strTime = timearr[3] + ":" + timearr[4]
            uum.strName = m.number!
            uumf.showTime = true
            uumf.message = uum
          
            
            return uumf
        }
        
        chatModel.dataSource = NSMutableArray(array: messages)
        tableView.reloadData()
        
    }
    
    func sendSMS(message:String) {
        guard (!isEmpty(string: phoneNum) && phoneNum!.isPhoneNumber()) else {
            SVProgressHUD.showError(withStatus: "Error Receiver")
            return
        }
        net_sendSMS(number: phoneNum!, message: message) {[weak self] (success) in
            if success {
                let dic : [String : Any] = ["strContent":message,"type":0]
                self!.inputV.textViewInput.text = "";
                self!.dealTheFunctionData(dic: dic)
            }
        }
    }
}

extension SMSDetailVC : UITableViewDataSource,
UITableViewDelegate ,UUInputFunctionViewDelegate{
    
    private func tableViewScrollToBottom() {
        guard chatModel.dataSource.count > 0 else {
            return
        }
        let indexPath = IndexPath(row: chatModel.dataSource.count-1, section: 0)
        tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
    
    private func dealTheFunctionData(dic:[String:Any]) {
        chatModel.addSpecifiedItem(dic);
        tableView.reloadData()
        tableViewScrollToBottom()
    }
    
    func uuInputFunctionView(_ funcView: UUInputFunctionView!, sendMessage message: String!) {
        sendSMS(message: message)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return chatModel.dataSource != nil ? chatModel.dataSource.count : 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UUMessageCell
        
        let model = chatModel.dataSource[indexPath.row] as! UUMessageFrame
        cell.messageFrame = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return (chatModel.dataSource[indexPath.row] as! UUMessageFrame).cellHeight
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

fileprivate class ReceiverInputView : UIView {
    var textChangedHandle : ((String?)->())?
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 80, height: 50))
        label.backgroundColor = clearColor
        label.text = "Receiver"
        label.textAlignment = .center
        label.textColor = textGray
        label.font = UIFont.boldSystemFont(ofSize: 18)
        return label
    }()
    
    private lazy var inputTF: UITextField = {
        let tf = UITextField(frame: CGRect(x: titleLabel.right, y: 4, width: screenWidth - titleLabel.right - 12, height: 42))
        tf.layer.borderColor = textGray.cgColor
        tf.layer.borderWidth = 0.5
        tf.cornerRadius(radius: 4)
        tf.font = UIFont.systemFont(ofSize: 18)
        tf.textColor = blackColor
        tf.addTarget(self, action: #selector(valueChanged), for: .editingDidEnd)
        return tf
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func valueChanged() {
        if textChangedHandle != nil {
            textChangedHandle!(inputTF.text)
        }
    }
    
    private func configView() {
        addSubview(titleLabel)
        addSubview(inputTF)
    }
}
